package service

import (
	"context"
	"errors"
	"patient-srv/basic/config"
	patient "patient-srv/basic/proto"
	"patient-srv/handler/model"
	"time"

	"gorm.io/gorm"
)

// GetOrderList 获取订单列表
func (s *PatientServiceServer) GetOrderList(ctx context.Context, req *patient.GetOrderListRequest) (*patient.OrderListResponse, error) {
	var orders []model.Order
	query := config.GlobalDB.Where("user_id = ?", req.UserId)

	// 如果指定订单类型，添加条件
	if req.OrderType > 0 {
		query = query.Where("order_type = ?", req.OrderType)
	}

	// 分页
	page := req.Page
	pageSize := req.PageSize
	if page < 1 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = 10
	}
	offset := (page - 1) * pageSize

	// 查询总数
	var total int64
	query.Model(&model.Order{}).Count(&total)

	// 查询订单列表
	err := query.Order("id DESC").
		Offset(int(offset)).
		Limit(int(pageSize)).
		Find(&orders).Error

	if err != nil {
		return nil, err
	}

	var result []*patient.Order
	for _, order := range orders {
		result = append(result, &patient.Order{
			Id:        order.ID,
			OrderNo:   order.OrderNo,
			UserId:    order.UserID,
			OrderType: int32(order.OrderType),
			Status:    int32(order.Status),
			Amount:    order.Amount,
			CreatedAt: order.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt: order.UpdatedAt.Format("2006-01-02 15:04:05"),
		})
	}

	return &patient.OrderListResponse{
		Message: "获取成功",
		Orders:  result,
		Total:   int32(total),
	}, nil
}

// GetOrderDetail 获取订单详情
func (s *PatientServiceServer) GetOrderDetail(ctx context.Context, req *patient.GetOrderDetailRequest) (*patient.OrderDetailResponse, error) {
	var order model.Order
	err := config.GlobalDB.Where("id = ? AND user_id = ?", req.OrderId, req.UserId).First(&order).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &patient.OrderDetailResponse{Message: "订单不存在"}, nil
		}
		return nil, err
	}

	return &patient.OrderDetailResponse{
		Message: "获取成功",
		Order: &patient.Order{
			Id:        order.ID,
			OrderNo:   order.OrderNo,
			UserId:    order.UserID,
			OrderType: int32(order.OrderType),
			Status:    int32(order.Status),
			Amount:    order.Amount,
			CreatedAt: order.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt: order.UpdatedAt.Format("2006-01-02 15:04:05"),
		},
	}, nil
}

// CancelOrder 取消订单
func (s *PatientServiceServer) CancelOrder(ctx context.Context, req *patient.CancelOrderRequest) (*patient.BaseResponse, error) {
	// 查询订单
	var order model.Order
	err := config.GlobalDB.Where("id = ? AND user_id = ?", req.OrderId, req.UserId).First(&order).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &patient.BaseResponse{Message: "订单不存在"}, nil
		}
		return nil, err
	}

	// 检查订单状态，只有待支付状态可以取消
	if order.Status != 1 {
		return &patient.BaseResponse{Message: "订单状态不允许取消"}, nil
	}

	// 更新订单状态为已取消
	if err := config.GlobalDB.Model(&order).Updates(map[string]interface{}{
		"status":     3,
		"remark":     req.Reason,
		"updated_at": time.Now(),
	}).Error; err != nil {
		return nil, err
	}

	return &patient.BaseResponse{Message: "取消成功"}, nil
}

// CreateOrder 创建订单
func (s *PatientServiceServer) CreateOrder(ctx context.Context, req *patient.CreateOrderRequest) (*patient.CreateOrderResponse, error) {
	// 生成订单号
	orderNo := model.GenerateOrderNo(int(req.OrderType))

	// 创建订单
	order := &model.Order{
		OrderNo:   orderNo,
		UserID:    req.UserId,
		OrderType: int(req.OrderType),
		Status:    1, // 待支付
		Amount:    req.Amount,
		RelatedID: req.RelatedId,
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
	}

	if err := config.GlobalDB.Create(order).Error; err != nil {
		return nil, err
	}

	return &patient.CreateOrderResponse{
		Message: "创建成功",
		OrderId: order.ID,
		OrderNo: order.OrderNo,
	}, nil
}
